import React, { useState, useEffect } from 'react';
import AppRouter from './router/AppRouter';
import './styles/globals.css';

function App() {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState('');

  // 从localStorage恢复用户状态
  useEffect(() => {
    const savedToken = localStorage.getItem('token');
    const savedUser = localStorage.getItem('user');

    if (savedToken && savedUser) {
      try {
        setToken(savedToken);
        const parsedUser = JSON.parse(savedUser);
        // 确保用户对象中包含isAdmin属性
        if (parsedUser && typeof parsedUser.isAdmin === 'undefined' && parsedUser.data) {
          parsedUser.isAdmin = parsedUser.data.isAdmin;
        }
        setUser(parsedUser);
      } catch (error) {
        console.error('恢复用户状态失败:', error);
        handleLogout();
      }
    }
  }, []);

  const handleLogin = (userData, userToken) => {
    // 确保用户对象中包含isAdmin属性
    if (userData && typeof userData.isAdmin === 'undefined' && userData.data) {
      userData.isAdmin = userData.data.isAdmin;
    }
    setUser(userData);
    setToken(userToken);
    localStorage.setItem('token', userToken);
    localStorage.setItem('user', JSON.stringify(userData));
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setUser(null);
    setToken('');
  };

  return (
      <AppRouter
          user={user}
          token={token}
          onLogin={handleLogin}
          onLogout={handleLogout}
          setUser={setUser}
      />
  );
}

export default App;